/*此模块是用来遍历指定目录——————将目录里的文件填进数据库*/
#include "head.h"

int file_root(char buff[16])            //用来判断文件权限
{
    int root = 0;
    struct stat buf;
    char buff_1[24] = {0};

    sprintf(buff_1, "./file/%s", buff);
    stat(buff_1, &buf);
    
    if (buf.st_mode & S_IRUSR)
    {
        root += 4;
    }
    if (buf.st_mode & S_IWUSR)
    {
        root += 2;
    }
    if (buf.st_mode & S_IXUSR)
    {
        root += 1;
    }
    return root;
}

int open_file(MYSQL **mysql)            //用来遍历目录并把目录的文件写进数据库
{
    int root = 0;
    char buff[16] = {0};
    char sort[5] = {0};
    char query[128] = {0};

    DIR *dp = opendir("./file"); // 打开指定目录
    if (NULL == dp)
    {
        perror("open dir");
        return -1;
    }

    struct dirent *dir = NULL;
    while (1)
    {
        dir = readdir(dp); // 便利目录下文件
        if (NULL == dir)
        {
            printf("读取完毕\n");
            break;
        }

        if (dir->d_name[0] != '.') // 去掉隐藏文件
        {
            bzero(buff, sizeof(buff));
            strcpy(buff, dir->d_name);
            root = file_root(buff);
            bzero(query, sizeof(query));
            sprintf(query, "insert into file (file_name,file_sort,file_root) values('%s',%d,%d)", buff, dir->d_type, root);
            if (mysql_real_query(*mysql, query, strlen(query)))
            {
                printf("文件信息录入中\n");
            }
        }
    }
    closedir(dp);
}

/*主要模块*/
int file_data()
{
    char buf[16] = {"文件信息"};
    MYSQL *mysql = mysql_op(buf);       //用来打开数据库

    open_file(&mysql);
    mysql_close(mysql);
    return 0;
}
